
var isMicExist = false 

// h5检测是否有麦克风
function hasMicrophone() {
  return new Promise( resolve=>{
    //检测并请求访问麦克风
    navigator.mediaDevices.getUserMedia({ audio: true })
    .then(function(stream) {
      console.log("有麦克风");
      resolve(true)
    })
    .catch(function(error) {
      console.log("没有麦克风或访问被拒绝");
      resolve(false)
    });
  })
}

async function initMicrophone(callback) {
  
  function getAudioInputDevices() {
    return new Promise(resolve=>{
      if (navigator?.mediaDevices?.enumerateDevices) {
        navigator.mediaDevices.enumerateDevices().then(devices => {
          const audioInputs = devices.filter(device => device.kind === 'audioinput')
          resolve(audioInputs)
        });
      } else {
        resolve([])
      }
    })
  }
  
  isMicExist = await hasMicrophone()
  if (callback) callback(isMicExist ? 'mic_in' : 'mic_out');
  
  // var deviceList = await getAudioInputDevices();
  // console.log('=== old list:', JSON.stringify(deviceList)) 
  
  // 监听设备变化
  navigator?.mediaDevices?.addEventListener('devicechange', async ()=>{
    // let list = await getAudioInputDevices();
    // console.log('=== 设备发生变化: length, list:', list.length, JSON.stringify(list)) 
    
    // // 检查 list 和 deviceList 内容是否一致 
    // let isSameList = isEqual(list, deviceList) 
    // console.log('=== 输入设备是否变化: ', !isSameList) 
    // if (!isSameList && callback) {
    //   callback();
    // }
    // deviceList = list 
    
    let ret = await hasMicrophone() 
    console.log('=== has microphone: ', ret) 
    if (ret != isMicExist) {
      isMicExist = ret 
      callback(isMicExist ? 'mic_in' : 'mic_out') 
    }
  });
} 

function isEqual(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false;
  }
 
  for (let i = 0; i < arr1.length; i++) {
    const obj1 = arr1[i];
    const obj2 = arr2[i];
 
    if (Object.keys(obj1).length !== Object.keys(obj2).length) {
      return false;
    }
 
    for (let key in obj1) {
      if (obj1.hasOwnProperty(key) && obj2.hasOwnProperty(key)) {
        if (obj1[key] !== obj2[key]) {
          return false;
        }
      } else {
        return false;
      }
    }
  }
  
  return true;
}
 





export default {
  hasMicrophone,
  initMicrophone,
}
